<?php

namespace App\Http\Controllers;

use App\Http\Requests\AddressController\AddAddressRequest;
use App\Http\Requests\AddressController\EditAddressRequest;
use App\Http\Resources\AddressResource;
use App\Models\Address;
use App\Models\Coin;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class AddressController extends Controller
{
    /**
     * 地址列表.
     *
     * @param Coin $coin
     *
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Coin $coin)
    {
        $address = Address::select(['id', 'note', 'address'])
            ->when($coin->exists, function (Builder $query) use ($coin) {
                return $query->where('coin_id', $coin->id);
            })
            ->where('user_id', Auth::id())
            ->orderByDesc('id')
            ->get();

        return AddressResource::collection($address);
    }

    /**
     * 添加地址.
     *
     * @param AddAddressRequest $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(AddAddressRequest $request)
    {
        // 最多添加20个地址
        if (Address::where('user_id', Auth::id())->where('coin_id', $request->input('coin_id'))->count() >= 20) {
            $this->error(20001);
        }

        $address = new Address();
        $address->user_id = Auth::id();
        $address->address = $request->input('address');
        $address->coin_id = $request->input('coin_id');
        $address->note = $request->input('note');
        $address->tag = $request->input('tag');
        $address->save();

        return $this->null();
    }

    /**
     * 编辑地址.
     *
     * @param Address $address
     * @param EditAddressRequest $request
     * @return \Illuminate\Http\Response
     */
    public function edit(Address $address, EditAddressRequest $request)
    {
        if ($address->user_id !== Auth::id()) {
            $this->error(403);
        }

        $address->address = $request->input('address');
        $address->note = $request->input('note');
        $address->tag = $request->input('tag');
        $address->save();

        return $this->null();
    }

    /**
     * 删除地址.
     *
     * @param Address $address
     *
     * @return \Illuminate\Http\Response
     *
     * @throws \Exception
     */
    public function destroy(Address $address)
    {
        if ($address->user_id == Auth::id()) {
            $address->delete();
        }

        return $this->null();
    }
}
